package security_rule

import (
	error_constants "app/app_src/framework/constant/error"
	web_constants "app/app_src/framework/constant/web"
	"app/app_src/framework/i18n"
	current_subject "app/app_src/framework/security/current/subject"
	security_strategy "app/app_src/framework/security/strategy"
	context_path_util "app/app_src/framework/util/web/context_path"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

func RequireAuthed(ctx *gin.Context, subject *current_subject.Subject) bool {
	request := ctx.Request
	path := request.URL.Path

	if subject == nil {
		// 根据请求信息，决定返回的结果格式
		if strings.HasSuffix(path, web_constants.URL_PREFIX_API) {
			ctx.PureJSON(http.StatusUnauthorized, gin.H{
				web_constants.JSON_RESULT_ERROR_CODE: error_constants.UNAUTHORIZED_DENIED,
				web_constants.JSON_RESULT_ERROR_MSG:  i18n.T("访问被拒绝！"),
			})
		} else {
			ctx.Redirect(http.StatusFound, context_path_util.WithContextPath(web_constants.URL_LOGIN_PAGE))
		}

		return false
	}

	if strings.HasPrefix(path, context_path_util.WithContextPath(web_constants.URL_PREFIX_API)) {
		csrfTokenCheckResult := security_strategy.CallCheckCsrfTokenFunc(ctx)

		if !csrfTokenCheckResult {
			ctx.PureJSON(http.StatusForbidden, gin.H{
				web_constants.JSON_RESULT_ERROR_CODE: error_constants.WRONG_CSRF_TOKEN,
				web_constants.JSON_RESULT_ERROR_MSG:  i18n.T("会话令牌失效，请稍后重试！"),
			})

			return false
		}
	}

	return true
}
